// 暴力解法
; (function () {
    //return
    /**
   * @param {number[]} heights
   * @return {number}
   */
    var largestRectangleArea = function (heights) {
        let result = 0
        let len = heights.length
        for (let index = 0; index < heights.length; index++) {
            // 这个是当前的高度
            const element = heights[index];

            let left = -1;
            let right = len
            for (let val = index + 1; val < heights.length; val++) {
                // 这个当前高度的后面所有高度
                const num = heights[val];
                if (num < element) {
                    right = val
                    break
                }

            }

            for (let val = index - 1; val >= 0; val--) {
                // 这个当前高度的前面所有高度
                const num = heights[val];
                if (num < element) {
                    left = val
                    break
                }

            }



            result = Math.max(result, (right - left - 1) * element)

        }

        return result
    };
    let arr = [2, 4]

    largestRectangleArea(arr)
})();

// 暴力解法的优化, 单调栈的形式

; (function () {
    //return
    /**
   * @param {number[]} heights
   * @return {number}
   */
    var largestRectangleArea = function (heights) {
        heights.push(-1)
        heights.unshift(-1)
        let stack = []
        let result = 0
        for (let index = 0; index < heights.length; index++) {
            const num = heights[index];


            // 这个判断的意思是 stack里面有值
            // 同事栈顶的值比,当前遍历的值大, 
            // 栈顶的的值就走到头了.
            // 可以计算栈顶值的最大矩形值了

            while (stack.length > 1 && heights[stack.at(-1)] > num) {
                let curIndex = stack.pop()
                let curNum = heights[curIndex]
                let leftIndex = stack.at(-1)
                result = Math.max(result, ((index - leftIndex - 1) * curNum))
            }

            if (stack.length === 1 || stack.length === 0) {
                stack.push(index)
                continue
            }

            if (heights[stack.at(-1)] !== num) {
                stack.push(index)
                continue
            }

            if (heights[stack.at(-1)] === num) {
                stack[stack.length - 1] = index
            }


        }
        return result
    };

    let arr = [0, 1, 0, 1]
    // let arr = [-1,2, 1, 5, 6, 2, 3,-1]
    largestRectangleArea(arr)
})();

